########################################################################################
##  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING THIS SOFTWARE
##
##  By downloading, copying, installing or using the software you agree to this license.
##  If you do not agree to this license, do not download, install, copy or use the software.
##
## Copyright (C) 2013, AerVision Technologies Pty Ltd, all rights reserved.
##
## Redistribution and use in source and binary forms, with or without modification,
## are permitted provided that the following conditions are met:
##
##   * Redistribution's of source code must retain the above copyright notice,
##     this list of conditions and the following disclaimer.
##
##   * Redistribution's in binary form must reproduce the above copyright notice,
##     this list of conditions and the following disclaimer in the documentation
##     and/or other materials provided with the distribution.
##
##   * The name of AerVision Technologies, may not be used to endorse or promote products
##     derived from this software without specific prior written permission.
##
## This software is provided by the copyright holders and contributors to demonstrate 
## www.AerCloud.net Framework as a Service API (FaaS), "as is" and
## any express or implied warranties, including, but not limited to, the implied
## warranties of merchantability and fitness for a particular purpose are disclaimed.
## In no event shall the copyright holder or contributors be liable for any direct,
## indirect, incidental, special, exemplary, or consequential damages
## (including, but not limited to, procurement of substitute goods or services;
## loss of use, data, or profits; or business interruption) however caused
## and on any theory of liability, whether in contract, strict liability,
## or tort (including negligence or otherwise) arising in any way out of
## the use of this software, even if advised of the possibility of such damage.
########################################################################################

import thread

from logging import getLogger

from Tkinter import Frame, Label, Menu
from aercloudclient.utils.ImageLoader import ImageLoader

from aercloudclient.gui.widgets import ScrolledFrame
from aercloudclient.utils.AerCloudNet_Interface import AerCloudNet_Interface

logging = getLogger(__name__)

class LoadingFrame(Frame):
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)            
        Label(self, text="Loading...", font=("Helvetica", 30)).pack(fill='both', expand=1)
    
class BrowseDatabaseWindow:

    def __init__(self, master):
        master.protocol('WM_DELETE_WINDOW', self.close_windows)
        master.wm_title("AerCloud.net Demo - Database Browser")
        master.minsize(420, 400)
        self.master = master
        self.main_frame = Frame(self.master)
        self.main_frame.pack(fill='both', expand=1)
        self.main_frame.grid_rowconfigure(0, weight=1)
        self.main_frame.grid_columnconfigure(0, weight=1)
        self.sframe = None
        self.loading_frame = LoadingFrame(self.main_frame)
        self.loading_frame.grid(row=0, column=0, sticky="nsew")
        self.RefreshData()
    
    def loading(self):
        self.loading_frame.tkraise()
        
    def onDelete(self):
        logging.debug("Delete: %s" % (self.popup_name))
        AerCloudNet_Interface.DeleteName(self.popup_name);
        self.RefreshData()
        
    def onPopup(self, event, name):
        self.popup_name = name
        self.menu.post(event.x_root, event.y_root)

    def RefreshView(self, imageFrame, personName):
        result = AerCloudNet_Interface.GetImageNames(personName);
        for imageName in result:
            lbl = Label(imageFrame, text="")
            lbl.pack(side='left', anchor='w')
            lbl.bind("<3>", lambda event, name=personName: self.onPopup(event, name))
            img = ImageLoader(lbl, personName, imageName)
            self.image.append(img)

    def RefreshAction(self):
        try:
            result = AerCloudNet_Interface.GetNames()
            self.main_frame.after(0, self.sframe.tkraise)
            row = 1
            for i in result:
                Label(self.frame, text="").grid(row=row, column=0)
                lbl = Label(self.frame, text=i)
                lbl.grid(row=row, column=1)
                lbl.bind("<3>", lambda event, name=i: self.onPopup(event, name))
                imageFrame = Frame(self.frame, background='white')
                imageFrame.grid(row=row, column=2, sticky='we')
                thread.start_new_thread(self.RefreshView, (imageFrame, i))
                row += 1
        except Exception, ex:
            logging.error(str(ex))
            self.close_windows()
                    
    def RefreshData(self):
        self.main_frame.after(0, self.loading)
        if self.sframe != None:
            self.frame.destroy()
            self.sframe.destroy()
        self.sframe = ScrolledFrame(self.main_frame)
        self.sframe.grid(row=0, column=0, sticky="nsew")
        self.frame = Frame(self.sframe.interior)
        self.frame.pack(fill='both', expand=1)
        Label(self.frame, text="Tags", width=15, relief='raised').grid(row=0, column=0, sticky='we')
        Label(self.frame, text="Name", relief='raised').grid(row=0, column=1, sticky='we')
        Label(self.frame, text="Image", relief='raised').grid(row=0, column=2, sticky='we')
        # create a popup menu
        self.menu = Menu(self.frame, tearoff=0)
        self.menu.add_command(label="Delete", command=self.onDelete)
        self.image = []        
        thread.start_new_thread(self.RefreshAction, ())
        
    def close_windows(self):
        self.master.destroy()
        